package com.swgk.core.util;

import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;

import androidx.cardview.widget.CardView;
import androidx.core.util.Pair;

import com.google.gson.Gson;

import com.swgk.core.BuildConfig;
import com.swgk.core.R;
import com.swgk.core.base.api.APIManager;
import com.swgk.core.base.api.AppFolwLogApi;
import com.swgk.core.base.aroute.AppRouteConstant;
import com.swgk.core.base.model.entity.BaseEntity;
import com.swgk.core.common.utils.ActivityJump;
import com.swgk.core.dialog.DialogHelper;
import com.swgk.core.dialog.RoundDialog;
import com.swgk.core.mmkvutil.MkvUtils;
import com.swgk.core.view.entity.PermissionEntity;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;


/**
 * 用户信息操作类
 */
public class UserOperating {
    private final String USER_OPERATING_CACHE = "USER_OPERATING_CACHE";
    /***
     * 用户数据
     */
    private PermissionEntity mUserInfo;

    private UserOperating() {
    }

    private static class Single {
        private static final UserOperating INSTANCE = new UserOperating();
    }

    public static UserOperating getInstance() {
        return Single.INSTANCE;
    }

    /**
     * 刷新数据
     */
    public void refresh() {
        //未登录不获取
        if (!isLogged()) return;
        //获取用户数据
        //TODO 接口有时候报错，改为不提示报错内容 Callback
        APIManager.getInstance(BuildConfig.BASE_URL_USER).create(AppFolwLogApi.class).getLogisticsPermissions().enqueue(new Callback<BaseEntity<PermissionEntity>>() {
            @Override
            public void onResponse(Call<BaseEntity<PermissionEntity>> call, Response<BaseEntity<PermissionEntity>> response) {
                DialogHelper.dismissProgressDialog();
                if (response.body() == null) {
                    return;
                }
                if (response.body().getData() == null) return;
                if (response.body().getState().equals("ok")) {
                    SharedPreferenceUtil.getInstance().saveData(SharedPreferenceUtil.COM_TYPE, response.body().getData().getUserType());
                    setUserInfo(response.body().getData());
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<PermissionEntity>> call, Throwable t) {
                DialogHelper.dismissProgressDialog();
            }
        });
    }

    /**
     * 是否已登录
     *
     * @return true：已登录  false：未登录
     */
    public boolean isLogged() {
        String token = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LOGIN_TOKEN, "");
        return !TextUtils.isEmpty(token);
    }

    /**
     * 获取当前登录者身份
     *
     * @return 0个人 1企业 2团队
     */
    public int getUserIdentity() {
        return SharedPreferenceUtil.getInstance().getSaveIntData(SharedPreferenceUtil.COM_TYPE, 0);
    }

    /**
     * 登录身份是否是企业
     *
     * @return true：是  false：否
     */
    public boolean isCompany() {
        //0个人 1企业 2团队
        int type = SharedPreferenceUtil.getInstance().getSaveIntData(SharedPreferenceUtil.COM_TYPE, 0);
        return type == 1;
    }

    /**
     * 登录身份是否是团队
     *
     * @return true：是  false：否
     */
    public boolean isTeam() {
        //0个人 1企业 2团队
        int type = SharedPreferenceUtil.getInstance().getSaveIntData(SharedPreferenceUtil.COM_TYPE, 0);
        return type == 2;
    }

    /**
     * 登录身份是否是个人
     *
     * @return true：是  false：否
     */
    public boolean isPersonal() {
        //0个人 1企业 2团队
        int type = SharedPreferenceUtil.getInstance().getSaveIntData(SharedPreferenceUtil.COM_TYPE, 0);
        return type == 0;
    }

    /**
     * 是否已认证实名
     *
     * @return true：已认证  false：未认证
     */
    public boolean isAuthRealName() {
        return getUserInfo() != null && getUserInfo().getIsRealName() == 1;
    }

    /**
     * 是否已认证司机
     *
     * @return true：已认证  false：未认证
     */
    public boolean isAuthDriver() {
        return getUserInfo() != null && getUserInfo().getDriverAuth() != null && getUserInfo().getDriverAuth().getStatus() == 1;
    }

    /**
     * 是否已认证团队
     *
     * @return true：已认证  false：未认证
     */
    public boolean isAuthOwner() {
        return getUserInfo() != null && getUserInfo().getTeamRespVO() != null;
    }

    /**
     * 是否已认证企业
     *
     * @return true：已认证  false：未认证
     */
    public boolean isAuthEnterprise() {
        return getUserInfo() != null && !TextUtils.isEmpty(getUserInfo().getCompanyNo());
    }

    /**
     * 是否已认证货运中介
     *
     * @return true：已认证  false：未认证
     */
    public boolean isAuthAgentComputer() {
        if (BuildConfig.BASE_URL.equals("http://api.sgbwl.com/sgb-app/")) {//测试服判断
            return getUserInfo() != null
                    && getUserInfo().getTeamRespVO() != null
                    && "202012014306139".equals(getUserInfo().getTeamRespVO().getBusinessTypeNo());
        }
        return getUserInfo() != null
                && getUserInfo().getTeamRespVO() != null
                && "1333351902414508032".equals(getUserInfo().getTeamRespVO().getBusinessTypeNo());
    }

    /**
     * 是否已开通资金账户
     *
     * @return true：已开通  false：未开通
     */
    public boolean isOpenFundAccount() {
        if (isCompany()) {
            //判断公司资金账户
            return getUserInfo() != null && getUserInfo().isOpenFundsAccount();
        } else {
            //判断个人资金账户
            return getUserInfo() != null && getUserInfo().isDriverOpenFundsAccount();
        }
    }

    /**
     * 获取当前用户no
     */
    public String getUserNo() {
        String no = "";
        if (getUserInfo() != null) {
            no = getUserInfo().getUserNo();
        }
        return no;
    }

    /**
     * 获取当前用户真实姓名
     */
    public String getUserRealName() {
        String name = "";
        if (getUserInfo() != null) {
            name = getUserInfo().getRealName();
        }
        return name;
    }

    /**
     * 获取手机号
     */
    public String getPhone() {
        String phone = "";
        if (getUserInfo() != null) {
            phone = getUserInfo().getTelPhone();
        }
        return phone;
    }

    /**
     * 是否有认证车辆
     */
    public boolean hasCar() {
        boolean hasCar = false;
        if (getUserInfo() != null) {
            hasCar = getUserInfo().isHasCar();
        }
        return hasCar;
    }

    /**
     * 获取当前登录身份的团队名称或者公司No
     */
    public String getTeamOrCompanyNameNo() {
        String no = "";
        if (isCompany()) {
            no = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.COMPANY_NO, "");
        } else if (getUserInfo() != null && getUserInfo().getTeamRespVO() != null) {
            no = getUserInfo().getTeamRespVO().getNo();
        }
        return no;
    }

    /**
     * 获取当前登录身份的团队名称或者公司名称
     */
    public String getTeamOrCompanyName() {
        String name = "";
        if (isCompany()) {
            name = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.COMPANY_NAME, "");
        } else if (getUserInfo() != null && getUserInfo().getTeamRespVO() != null) {
            name = getUserInfo().getTeamRespVO().getName();
        }
        return name;
    }

    /**
     * 检查是否有公司某权限
     */
    public boolean hasCompanyPermission(String checkPermission) {
        return PermissionCheckUtil.hasCompanyPermission(checkPermission);
    }

    /**
     * 获取用户数据
     */
    public PermissionEntity getUserInfo() {
        //未登录则清空用户数据
        if (!isLogged()) {
            setUserInfo(new PermissionEntity());
        }
        //获取用户数据
        if (mUserInfo == null) {
            mUserInfo = getUserMsgEntity();
        }
        //判断是否是新建对象,因为注销事不能存null，所以存储的空对象
        if (mUserInfo != null && TextUtils.isEmpty(mUserInfo.getUserNo())) {
            return null;
        }
        return mUserInfo;
    }

    /**
     * 用户个人信息
     */
    public void setUserInfo(PermissionEntity userMsgEntity) {
        mUserInfo = null;
        Gson gson = new Gson();
        String userJson = gson.toJson(userMsgEntity);
//        SharedPreferenceUtil.getInstance().saveData(SharedPreferenceUtil.COM_TYPE, userMsgEntity.getUserType());
        MkvUtils.get().putString(MkvUtils.CommomData, USER_OPERATING_CACHE, userJson);
    }

    /**
     * 获取用户个人信息
     * 包含了用户名，电话，企业等一些信息
     */
    private PermissionEntity getUserMsgEntity() {
        String userJson = MkvUtils.get().getString(MkvUtils.CommomData, USER_OPERATING_CACHE, "");
        Gson gson = new Gson();
        PermissionEntity userInfo = null;
        if (!userJson.isEmpty()) {
            userInfo = gson.fromJson(userJson, PermissionEntity.class);
        }
        return userInfo;
    }

    /**
     * 清除用户基本信息
     */
    public void cleanCacheUser() {
        mUserInfo = null;
        MkvUtils.get().remove(MkvUtils.CommomData, USER_OPERATING_CACHE);
    }

    /**
     * 检查用户登录状态，未登录跳转登录页
     */
    public boolean isNotLogged(Context context) {
        if (!isLogged()) {
            //跳转登录
            ActivityJump.startActivity(AppRouteConstant.VerificationCodeLoginActivity, Pair.create("isJump", false));
            return true;
        }
        return false;
    }

    /**
     * 检查用户司机认证状态，未认证弹窗，点确定跳转司机认证页
     */
    public boolean isNotAuthDriver(Context context) {
        return isNotAuthDriver(context, true);
    }

    /**
     * 检查用户司机认证状态，未认证直接跳转司机认证页
     */
    public boolean isNotAuthDriver(Context context, boolean isShowAuthDialog) {
        if (!isAuthDriver()) {
            if (isShowAuthDialog) {
                showDriverDialog(context);
            } else if (!isAuthRealName()) {
                //跳转实名认证
                ActivityJump.startActivity(AppRouteConstant.CertificationActivity);
            } else {
                //跳转司机认证
                ActivityJump.startActivity(AppRouteConstant.AddDriverInfoActivity);
            }
            return true;
        }
        return false;
    }

    public boolean canNotLookGoodsBus(Context context) {
        //判断是否登录
        if (isNotLogged(context)) return true;
        if (isCompany()) {
            if (!hasCompanyPermission(PermissionCheckUtil.KEY_HUOYUANGUANLI)) {
                showCompanyPermissionDialog(context, "您查看承运商机的权限");
                return true;
            }
        } else if (isTeam()) {
            //判读是否是物流中介
            if (!isAuthAgentComputer()) {
                showAgentComputerDialog(context);
                return true;
            }
        } else if (isPersonal()) {
            //判断实名认证
            if (!isAuthRealName()) {
                showAuthPersonDialog(context);
                return true;
            }
        }
        return false;
    }

    public boolean canNotPublishGoods(Context context) {
        //判断是否登录
        if (isNotLogged(context)) return true;
        if (isTeam()) {
            //判读是否是物流中介
            if (!isAuthAgentComputer()) {
                showAgentComputerDialog(context);
                return true;
            }
        }
        return false;
    }

    public boolean canNotLookCarriageBus(Context context) {
        //判断是否登录
        if (isNotLogged(context)) return true;
        if (isCompany() || isTeam()) {
            showNeedDriverAuthDialog(context);
            return true;
        } else if (isPersonal()) {
            //判断实名认证
            if (isNotAuthDriver(context)) {
                return true;
            }
        }
        return false;
    }

    public void showNeedDriverAuthDialog(Context context) {
        AlertDialog dialog;
        LayoutInflater inflater = LayoutInflater.from(context);
        View layout;
        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        layout = inflater.inflate(R.layout.dialog_authen_driver_change, null);
        builder.setView(layout);
        builder.setCancelable(true);
        dialog = builder.show();
        dialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
        layout.findViewById(R.id.rl_authen_driver).setOnClickListener(view -> {
            ActivityJump.startActivity(AppRouteConstant.AuthActivity3);
            dialog.dismiss();
        });
        DisplayMetrics dm = new DisplayMetrics();
        //获取屏幕信息
        dm = UiUtil.getResources().getDisplayMetrics();
        int screenWidth = dm.widthPixels;
        int screenHeigh = dm.heightPixels;
        CardView cv = dialog.findViewById(R.id.cv_dialog);
        LinearLayout.LayoutParams linearParams = (LinearLayout.LayoutParams) cv.getLayoutParams(); //取控件textView当前的布局参数
        linearParams.width = screenWidth - 100;//
        cv.setLayoutParams(linearParams);
        dialog.findViewById(R.id.iv_cancel).setOnClickListener(v -> dialog.dismiss());
    }


    public void showDriverDialog(Context context) {
        //审核状态（0 待审核 1 审核通过 2 审核不通过），-1 未提交审核
        int status = -1;
        if (getUserInfo() != null && getUserInfo().getDriverAuth() != null) {
            status = getUserInfo().getDriverAuth().getStatus();
        }
        String content = "";
        String title = "提示";
        switch (status) {
            case -1:
                content = "当前功能需要认证司机，\n是否立即认证？";
                break;
            case 0:
                content = "司机认证审核中，请耐心等待审核结果";
                break;
            case 2:
                content = "司机认证未通过，请查看原因后重新认证";
                break;
        }
        int finalStatus = status;
        new RoundDialog.Builder(context)
                .title(title)
                .content(content)
                .contentGravity(Gravity.CENTER)
                .cancel("取消")
                .confirm(status == -1
                        ? "确定"
                        : "查看审核详情")
                .cancelable(false)
                .confirmCallback(v -> {
                    if (finalStatus != -1) {
                        //司机详情
                        ActivityJump.startActivity(AppRouteConstant.DriverInfoActivity);
                    } else {
                        //跳转司机认证
                        ActivityJump.startActivity(AppRouteConstant.AddDriverInfoActivity);
                    }
                })
                .show();
    }

    /**
     * 检查用户是否开通资金账户,2.0.2.1暂时只增加个人发布普通货源权限，后续待修改
     */
    public boolean isNotOpenFundAccount(Context context, String menuname) {
        //判断是否登录
        if (isNotLogged(context)) return true;
        if (isCompany()) {
            if (!hasCompanyPermission(menuname)) {
                switch (menuname) {
                    case PermissionCheckUtil.KEY_HUOYUANGUANLI:
                        showCompanyPermissionDialog(context, "您发布货源的权限");
                        break;
                    case PermissionCheckUtil.KEY_WODEXUNJIA:
                        showCompanyPermissionDialog(context, "您询价的操作权限");
                        break;
                    case PermissionCheckUtil.KEY_CHENGYUNSHANGJI:
                        showCompanyPermissionDialog(context, "您查看货车承运的权限");
                        break;
                }

                return true;
            }
            if (!isOpenFundAccount()) {
                showFundAccountDialog(context);
                return true;
            }
        } else if (isTeam()) {
            //判读是否是物流中介 2.1.5 去掉
            /*if (!isAuthAgentComputer()) {
                showAgentComputerDialog(context);
                return true;
            }*/
            if (!isOpenFundAccount()) {
                showFundAccountDialog(context);
                return true;
            }
        } else if (isPersonal()) {
            //判断实名认证
            if (!isAuthRealName()) {
                showAuthPersonDialog(context);
                return true;
            }
            if (!isOpenFundAccount()) {
                showFundAccountDialog(context);
                return true;
            }
        }
        return false;
    }

    /**
     * 展示公司权限弹窗
     */
    private void showCompanyPermissionDialog(Context context, String content) {
        new RoundDialog.Builder(context)
                .title("提示")
                .content(String.format("%s未授予%s。建议您联系管理员分配权限", getTeamOrCompanyName(), content))
                .contentGravity(Gravity.CENTER)
                .confirm("我知道了")
                .singleBtn(true)
                .show();
    }


    /**
     * 展示物流中介弹窗
     */
    private void showAgentComputerDialog(Context context) {
        new RoundDialog.Builder(context)
                .title("提示")
                .content("当前功能需认证经营类型为物流信息中介的团队，是否认证新团队")
                .contentGravity(Gravity.CENTER)
                .cancel("取消")
                .confirm("去认证")
                .cancelable(false)
                .confirmCallback(v -> ActivityJump.startActivity(AppRouteConstant.AuthActivity3))
                .show();
    }

    /**
     * 展示个人认证弹窗
     */
    private void showAuthPersonDialog(Context context) {
        new RoundDialog.Builder(context)
                .title("提示")
                .content("您当前未实名认证，是否立即认证？")
                .contentGravity(Gravity.CENTER)
                .cancel("取消")
                .confirm("确定")
                .cancelable(false)
                .confirmCallback(v -> ActivityJump.startActivity(AppRouteConstant.AuthActivity3))
                .show();
    }

    /**
     * 展示资金账户提示弹窗
     */
    private void showFundAccountDialog(Context context) {
        new RoundDialog.Builder(context)
                .title("提示")
                .content("开通在线收款账户后\n可使用此功能")
                .contentGravity(Gravity.CENTER)
                .cancel("知道了")
                .confirm("前往开户")
                .cancelable(false)
                .confirmCallback(v -> jumpToOpenAccount(context))
                .show();
    }

    /**
     * 定向跳转开通资金账户
     */
    public void jumpToOpenAccount(Context context) {
        ActivityJump.startActivity(AppRouteConstant.OpenAccountFirstActivity, Pair.create("isUser", !isCompany()));
    }

    /**
     * 判断是否登录和实名认证
     *
     * @param context
     * @return
     */
    public boolean isNotAuthReal(Context context) {
        //判断是否登录
        if (isNotLogged(context)) return true;
        boolean personAuth = SharedPreferenceUtil.getInstance().getSaveBooleanData(SharedPreferenceUtil.PERSON_AUTH, false);
        //判断实名认证
        if (!personAuth) {
            showAuthPersonDialog(context, "当前功能需要实名认证后才能操作\n" + "是否前往实名认证？", "去认证");
            return true;
        }

        return false;
    }

    /**
     * 展示个人认证弹窗,直接跳转实名认证页
     */
    private void showAuthPersonDialog(Context context, String content, String confirm) {
        new RoundDialog.Builder(context)
                .title("提示")
                .content(content)
                .contentGravity(Gravity.CENTER)
                .cancel("取消")
                .confirm(confirm)
                .cancelable(false)
                .confirmCallback(v -> ActivityJump.startActivity(AppRouteConstant.CertificationActivity, Pair.create("type", "1")))
                .show();
    }

    /**
     * 是否车主实名认证
     *
     * @param context
     * @param authTime
     * @return
     */
    public boolean IsAuth(Context context, Long authTime) {
        boolean isAuth = false;
        if (authTime != null) {
            isAuth = true;
        } else {
            MToast.showToast(context, "车主未实名认证");
        }
        return isAuth;
    }

    /**
     * 司机审核通过
     * @param context
     */
    public boolean hasNotDriverPermission(Context context) {
        //审核状态（0 待审核 1 审核通过 2 审核不通过），-1 未提交审核
        int status = -1;
        if (getUserInfo() != null && getUserInfo().getDriverAuth() != null) {
            status = getUserInfo().getDriverAuth().getStatus();
        }
        String content = "";
        switch (status) {
            case -1:
                new RoundDialog.Builder(context)
                        .title("提示")
                        .content("请先进行司机认证，才可使用该功能。")
                        .contentGravity(Gravity.CENTER)
                        .cancel("取消")
                        .confirm("去认证")
                        .cancelable(false)
                        .confirmCallback(v -> {
                            //跳转司机认证
                            ActivityJump.startActivity(AppRouteConstant.AddDriverInfoActivity);
                        })
                        .show();
                return true;
            case 0:
                MToast.showToast(context, "司机认证审核中，无法使用该功能");
                return true;
            case 2:
                content = "司机认证未通过，是否前往重新认证";
                new RoundDialog.Builder(context)
                        .title("温馨提示")
                        .content(content)
                        .contentGravity(Gravity.CENTER)
                        .cancel("取消")
                        .confirm("去认证")
                        .cancelable(false)
                        .confirmCallback(v -> {
                            //跳转司机认证
                            ActivityJump.startActivity(AppRouteConstant.DriverInfoActivity);
                        })
                        .show();
                return true;
        }
        return false;

    }

}
